package com.corpgovernment.organization.service.impl;

import cn.hutool.core.date.DateUtil;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.holder.TenantContextHolder;
import com.corpgovernment.common.utils.HttpHuToolUtils;
import com.corpgovernment.common.utils.LogSplicingUtils;
import com.corpgovernment.common.utils.Null;
import com.corpgovernment.organization.Bo.CommonSupplierUrlBo;
import com.corpgovernment.organization.Bo.GetOpenCardInfoMQBo;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.dataloader.BasicDataClientLoader;
import com.corpgovernment.organization.dataloader.db.MbSupplierCompanyLoader;
import com.corpgovernment.organization.dto.GetCardReq;
import com.corpgovernment.organization.dto.GetCardRsp;
import com.corpgovernment.organization.dto.OpenCardReq;
import com.corpgovernment.organization.dto.OpenCardRsp;
import com.corpgovernment.organization.entity.MbOpenCardMainTable;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeOpenCardLog;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeOpenCardRecord;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.mapper.MbOpenCardMainTableMapper;
import com.corpgovernment.organization.model.OpenCardEmployeeModel;
import com.corpgovernment.supplier.vo.OpenCardDetailListInfoVo;
import com.corpgovernment.supplier.vo.OpenCardListInfoVo;
import com.corpgovernment.supplier.vo.OpenCardMainTableVo;
import com.corpgovernment.organization.model.SupplierCompanyModel;
import com.corpgovernment.organization.mq.GetOpenCardInfoMQProducer;
import com.corpgovernment.organization.service.*;
import com.corpgovernment.supplier.constant.CommonConstant;
import com.corpgovernment.supplier.vo.OpenCardResultDetailVo;
import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.DateUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zl.cui
 * @date 2023/10/13
 * 携程开卡服务
 */
@Component
@Slf4j
public class CtripOpenCardServiceImpl implements CtripOpenCardService {
    @Autowired
    private OrganizationApollo organizationApollo;
    @Autowired
    private BasicDataClientLoader basicDataClientLoader;
    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private MbOrgEmployeeOpenCardRecordService orgEmployeeOpenCardRecordService;

    @Autowired
    private GetOpenCardInfoMQProducer getOpenCardInfoMQProducer;
    @Autowired
    private MbOrgEmployeeOpenCardLogService mbOrgEmployeeOpenCardLogService;
    @Autowired
    private MbSupplierCompanyLoader supplierCompanyLoader;
    @Autowired
    private RedissonClient redissonClient;
     RRateLimiter rateLimiter;
    private final static String PREFIX_OBT = "obt";
    private final static String FAILED_REASON = "未配置推送地址";
    private final static  String CTRIP_NOT_OPEN_CARD = "未查询到携程开卡记录，开卡失败";
    /**
     * 分销最多只能处理100条开卡数据
     */
    private final static int MAX_SIZE = 100;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private MbSupplierCompanyLoader mbSupplierCompanyLoader;
    @Autowired
    private MbOpenCardMainTableMapper mbOpenCardMainTableMapper;

    /**
     * 初始化限流器
     */
    @PostConstruct
    public void initRateLimiter(){
        RRateLimiter rateLimiter = redissonClient.getRateLimiter("OpenCardLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.SECONDS);
        this.rateLimiter = rateLimiter;
    }


    @Override
    public List<OpenCardEmployeeModel> openCard(String orgId, List<OpenCardEmployeeModel> openCardList, SupplierCompanyModel companyConfig) {
        if (CollectionUtils.isEmpty(openCardList)){
            return Collections.emptyList();
        }
        StringBuilder logContext = new StringBuilder();
        log.info("用户集合：{}", JsonUtils.toJsonString(openCardList));
        if (companyConfig == null){
            List<SupplierCompanyModel> companyConfigList = getParentConfig(orgId);
            if (CollectionUtils.isEmpty(companyConfigList) || StringUtils.isBlank(companyConfigList.get(0).getSubAccountCode())){
                log.error("orgId:{}配置为空", orgId);
                throw new CorpBusinessException(OrganizationResponseCodeEnum.COMPANY_ACCOUNT_CONFIG_EMPTY);
            }
             companyConfig = companyConfigList.get(0);
        }


        //获取请求地址
        CommonSupplierUrlBo commonUrl = CommonSupplierUrlBo.getCommonSupplierUrl(organizationApollo.getCtripUrl(),
                Null.or(companyConfig.getSupplierCorpId(), String::trim, null),
                Null.or(companyConfig.getSubAccountCode(), String::trim, null),
                logContext);
        if (Objects.isNull(commonUrl)){
            openCardList.forEach(t-> t.setOpenCardFailedContent(FAILED_REASON));
            return openCardList;
        }
        List<List<OpenCardEmployeeModel>> partitionedList = Lists.partition(openCardList, MAX_SIZE);
        List<OpenCardEmployeeModel> failedList = new ArrayList<>();
        partitionedList.forEach(t -> {
            List<OpenCardEmployeeModel> batchFailedList = this.ctripOpenCard(t, logContext, commonUrl);
            failedList.addAll(batchFailedList);
        });
        return failedList;
    }

    @Override
    public Long generateKey(Integer total,String orgId,String userName, SupplierCompanyModel companyConfig) {
        MbOpenCardMainTable mbOpenCardMainTable = new MbOpenCardMainTable();
        mbOpenCardMainTable.setTotal(total);
        mbOpenCardMainTable.setOrgId(orgId);
        mbOpenCardMainTable.setApplyUserName(userName);
        mbOpenCardMainTable.setSubAccountCode(companyConfig.getSubAccountCode());
        mbOpenCardMainTable.setSupplierAccountId(companyConfig.getSupplierAccountId());
        mbOpenCardMainTable.setSuccessNum(0);
        mbOpenCardMainTable.setApplySuccessNum(0);
        mbOpenCardMainTable.setDatachangeCreatetime(new Date());
        mbOpenCardMainTable.setDatachangeLasttime(new Date());
        mbOpenCardMainTableMapper.insert(mbOpenCardMainTable);
        return mbOpenCardMainTable.getId();
    }

    @Override
    public OpenCardListInfoVo getOpenCardResult(String orgId, int pageNum, int pageSize, String subAccountCode, String subAccountId) {
        PageHelper.orderBy("datachange_createtime desc");
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(MbOpenCardMainTable.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        if(StringUtils.isNotBlank(subAccountCode)){
            criteria.andEqualTo("subAccountCode", subAccountCode);
        }
        if(StringUtils.isNotBlank(subAccountId)){
            criteria.andEqualTo("supplierAccountId",subAccountId);
        }
        List<MbOpenCardMainTable> allInfoList = mbOpenCardMainTableMapper.selectByExample(example);
        PageInfo<MbOpenCardMainTable> pageInfo = new PageInfo<>(allInfoList);
        allInfoList = pageInfo.getList();
        if (CollectionUtils.isEmpty(allInfoList)){
            return null;
        }
        OpenCardListInfoVo openCardListInfo = new OpenCardListInfoVo();
        openCardListInfo.setCurrentPage(pageInfo.getPageNum());
        openCardListInfo.setTotalPage(pageInfo.getPages());
        openCardListInfo.setCount(pageInfo.getTotal());
        openCardListInfo.setPageSize(pageInfo.getPageSize());
        openCardListInfo.setOpenCardList(allInfoList.stream().map(t->{
            OpenCardMainTableVo openCardMainTable = new OpenCardMainTableVo();
            openCardMainTable.setApplyTime(Null.or(t.getDatachangeCreatetime(), o->DateUtils.format(o, "yyyy-MM-dd HH:mm:ss"),null));
            openCardMainTable.setTotal(t.getTotal());
            openCardMainTable.setSuccessNum(t.getSuccessNum());
            openCardMainTable.setApplyUserName("系统");
            openCardMainTable.setBatchNo(String.valueOf(t.getId()));
            openCardMainTable.setApplySuccessNum(t.getApplySuccessNum());
            openCardMainTable.setSupplierAccountId(t.getSupplierAccountId());
            openCardMainTable.setSubAccountCode(t.getSubAccountCode());
            Integer openCardFailedNum = mbOrgEmployeeOpenCardLogService.getFailedNum(t.getId(), 1);
            openCardMainTable.setApplyFailedNum(openCardFailedNum);
            Integer failedNum = mbOrgEmployeeOpenCardLogService.getFailedNum(t.getId(), 2);
            openCardMainTable.setFailedNum(failedNum);
            openCardMainTable.setOrgId(t.getOrgId());
            return openCardMainTable;
        }).sorted(Comparator.comparing(OpenCardMainTableVo::getApplyTime).reversed()).collect(Collectors.toList()));
        openCardListInfo.getOpenCardList();
        return openCardListInfo;
    }

    @Override
    public OpenCardDetailListInfoVo getOpenCardDetailResult(String orgId, String batchNo, int pageNum, int pageSize, Integer failedType) {
        OpenCardDetailListInfoVo openCardDetailListInfoVo = new OpenCardDetailListInfoVo();
        List<MbOrgEmployeeOpenCardLog> resultList = mbOrgEmployeeOpenCardLogService.getByBatchNo(Long.valueOf(batchNo),failedType, pageNum, pageSize,openCardDetailListInfoVo);
        if (CollectionUtils.isEmpty(resultList)){
            return null;
        }
         openCardDetailListInfoVo.setOpenCardList(resultList.stream().map(t->{
            OpenCardResultDetailVo openCardResultDetailVo = new OpenCardResultDetailVo();
            openCardResultDetailVo.setUid(t.getPlatUid());
            openCardResultDetailVo.setEmployeeName(t.getEmployeeName());
            openCardResultDetailVo.setFailedCode(Null.or(t.getFailedCode(), String::valueOf));
            openCardResultDetailVo.setFailedReason(t.getFailReason());
            return openCardResultDetailVo;
        }).collect(Collectors.toList()));
        return openCardDetailListInfoVo;
    }

    private List<OpenCardEmployeeModel> ctripOpenCard(List<OpenCardEmployeeModel> openCardList, StringBuilder logContext, CommonSupplierUrlBo commonUrl) {
        // 如果开卡是空不应该给分销传参数
        if (CollectionUtils.isEmpty(openCardList)){
            return Collections.emptyList();
        }
        OpenCardReq openCardReq = new OpenCardReq();
        List<OpenCardReq.AuthenticationInfo> authenticationInfoList = new ArrayList<>();
        for (int i = 0; i < openCardList.size(); i++) {
            OpenCardReq.AuthenticationInfo authenticationInfo = this.getAuthenticationInfo(i + 1, openCardList.get(i), commonUrl);
            authenticationInfoList.add(authenticationInfo);
        }
        openCardReq.setAuthenticationInfoList(authenticationInfoList);
        OpenCardRsp openCardRsp = this.openCardSupplier(commonUrl, openCardReq, logContext);
        List<OpenCardEmployeeModel> failedList = new ArrayList<>();
        if (Objects.nonNull(openCardRsp) && CollectionUtils.isNotEmpty(openCardRsp.getErrorMessageList())){
            for (OpenCardRsp.ErrorMessage message : openCardRsp.getErrorMessageList()){
                OpenCardEmployeeModel filedModel = openCardList.get(message.getSequence() - 1);
                filedModel.setOpenCardFailedContent(message.getMessage());
                addFailLog(filedModel.getUid(),filedModel.getName(), message.getMessage(),message.getErrorCode(), filedModel.getBatchNo(),1);
                failedList.add(filedModel);
            }
        }
        List<OpenCardEmployeeModel> openCardSuccessList = openCardList.stream().filter(t -> StringUtils.isBlank(t.getOpenCardFailedContent())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(openCardSuccessList)){
            return Collections.emptyList();
        }
        synchronized (this){
            mbOpenCardMainTableMapper.addApplySuccessNum(openCardSuccessList.get(0).getBatchNo(), openCardSuccessList.size());
        }

        openCardSuccessList.forEach(t -> {
           try {
               saveOpenCardRecord(commonUrl, t, logContext);
           } catch (Exception e) {
               log.error("保存开卡记录异常", e);
           }
       });

        return failedList;
    }

    /**
     * 调用供应商开卡
     * @param openCardReq
     * @return
     * @throws IOException
     */
    public OpenCardRsp openCardSupplier(CommonSupplierUrlBo commonSupplierUrlBo, OpenCardReq openCardReq, StringBuilder logContext) {
        try {
            CommonSupplierUrlBo.UrlInfo employeeOpenCard = commonSupplierUrlBo.getEmployeeOpenCard();
            String ticket = basicDataClientLoader.ctripTokenByCorpID(employeeOpenCard.getCorpId(), employeeOpenCard.getSupplierCode());
            openCardReq.setAppkey(String.format("%s_%s", "obk", employeeOpenCard.getCorpId()));
            openCardReq.setTicket(ticket);
            openCardReq.setCorporationID(employeeOpenCard.getCorpId());
            LogSplicingUtils.addLogContext(logContext, "员工开卡 req：%s", JsonUtils.toJsonString(openCardReq));
            String result = null;
            if (rateLimiter.tryAcquire(5, TimeUnit.SECONDS)){
                result = HttpHuToolUtils.httpHuToolPost("员工开卡", employeeOpenCard.getUrl(), JsonUtils.toJsonString(openCardReq));
            }
            LogSplicingUtils.addLogContext(logContext, "员工开卡 rsp：%s", result);
            return JsonUtils.parse(result, OpenCardRsp.class);
        }catch (Exception e){
            log.error("openCardSupplier error", e);
        }
        return null;
    }

    /**
     * 开卡信息组装
     * @param employeeInfo
     * @param commonUrl
     * @return
     */
    public OpenCardReq.AuthenticationInfo getAuthenticationInfo(int sequence, OpenCardEmployeeModel employeeInfo, CommonSupplierUrlBo commonUrl){
        CommonSupplierUrlBo.UrlInfo employeeOpenCard = commonUrl.getEmployeeOpenCard();
        OpenCardReq.AuthenticationInfo authenticationInfo = new OpenCardReq.AuthenticationInfo();
        OpenCardReq.Authentication authentication = new OpenCardReq.Authentication();
        authentication.setEmployeeID(this.getOpenCardUid(PREFIX_OBT, employeeInfo.getUid()));
        authentication.setSubAccountName(employeeOpenCard.getSubAccountName());
        authentication.setName(employeeInfo.getName());
        authentication.setMobilePhone(employeeInfo.getMobilePhone());
        if (StringUtils.isNotBlank(employeeInfo.getAreaCode())){
            String areaCode = employeeInfo.getAreaCode().replace("+", "");
            authentication.setCountryCode(Integer.parseInt(areaCode));
        }
        authentication.setEmail(employeeInfo.getEmail());
        authentication.setIsSendEMail(false);
        authentication.setBirthday(Optional.ofNullable(employeeInfo.getBirthday()).map(item -> DateUtil.format(item, "yyyy-MM-dd")).orElse(""));
        authentication.setGender(employeeInfo.getGender());
        if (StringUtils.isNotBlank(employeeInfo.getNationality())) {
            authentication.setNationality(StringUtils.split(employeeInfo.getNationality(), "|")[0]);
        }
        authentication.setDept5(employeeInfo.getCorporateEntity());
        authentication.setCorpEmailSendRules(buildDefaultEmailSendRules());
        authenticationInfo.setSequence(sequence);
        authenticationInfo.setAuthentication(authentication);
        return authenticationInfo;
    }

    /**
     * 目前发送邮件只有酒店商公账支付的场景需要进行配置
     * @return
     */
    private List<OpenCardReq.CorpEmailSendRuleEntity> buildDefaultEmailSendRules(){
        OpenCardReq.CorpEmailSendRuleEntity corpEmailSendRuleEntity = new OpenCardReq.CorpEmailSendRuleEntity();
        corpEmailSendRuleEntity.setEmailSendRuleValid("T");
        corpEmailSendRuleEntity.setEmailSendNode("I");
        corpEmailSendRuleEntity.setIsSendContactor("T");
        corpEmailSendRuleEntity.setBusinessType(4);

        return Collections.singletonList(corpEmailSendRuleEntity);
    }
    /**
     * 获取供应商开卡信息
     * @param commonSupplierUrlBo
     * @param uid
     * @param logContext
     * @return
     */
    public GetCardRsp getCardInfo(CommonSupplierUrlBo commonSupplierUrlBo, String uid, StringBuilder logContext){
        try {
            CommonSupplierUrlBo.UrlInfo getOpenCardInfo = commonSupplierUrlBo.getGetOpenCardInfo();
            String ticket = basicDataClientLoader.ctripTokenByCorpID(getOpenCardInfo.getCorpId(), getOpenCardInfo.getSupplierCode());
            GetCardReq getCardReq = new GetCardReq();
            getCardReq.setTicket(ticket);
            getCardReq.setCorpID(getOpenCardInfo.getCorpId());
            getCardReq.setEmployeeID(this.getOpenCardUid(PREFIX_OBT, uid));
            LogSplicingUtils.addLogContext(logContext, "获取开卡信息 req：%s", JsonUtils.toJsonString(getCardReq));
            String result = HttpHuToolUtils.httpHuToolPost("获取开卡信息", getOpenCardInfo.getUrl(), JsonUtils.toJsonString(getCardReq));
            LogSplicingUtils.addLogContext(logContext, "获取开卡信息 req：%s", result);
            return JsonUtils.parse(result, GetCardRsp.class);
        }catch (Exception e){
            log.error("{}", e);
        }
        return null;
    }

    /**
     * 避免事物未提交问题-先睡眠 后查询未查到则无需处理
     * @param uid
     * @return
     * @throws InterruptedException
     */
    public MbOrgEmployeeInfo compensateGetEmployee(String uid) throws InterruptedException {
        Thread.sleep(2000);
        log.info("compensateGetEmployee");
        return organizationEmployeeService.findByUid(uid);
    }

    /**
     * 开卡失败日志
     * @return
     */
    public void addFailLog(String uid, String name, String failReason,String failedCode, Long batchNo,Integer failedType){
        MbOrgEmployeeOpenCardLog openCardLog = new MbOrgEmployeeOpenCardLog();
        openCardLog.setPlatUid(uid);
        openCardLog.setEmployeeName(name);
        openCardLog.setFailReason(failReason);
        openCardLog.setDatachangeCreatetime(new Date());
        openCardLog.setDatachangeLasttime(new Date());
        openCardLog.setBatchNo(batchNo);
        openCardLog.setFailedType(failedType);
        openCardLog.setFailedCode(failedCode);
        mbOrgEmployeeOpenCardLogService.insert(openCardLog);
    }

    /**
     * 获取拼接卡号
     * @param prefix
     * @param uid
     * @return
     */
    public String getOpenCardUid(String prefix, String uid){
        return String.format("%s_%s_%s", prefix, TenantContext.getTenantId(), uid);
    }

    /**
     * 获取开卡信息
     * @param commonSupplierUrlBo
     * @param logContext
     * @throws InterruptedException
     */
    public void saveOpenCardRecord(CommonSupplierUrlBo commonSupplierUrlBo, OpenCardEmployeeModel openCardEmployeeModel, StringBuilder logContext){
        GetCardRsp cardInfo = this.getCardInfo(commonSupplierUrlBo, openCardEmployeeModel.getUid(), logContext);
        if (Objects.isNull(cardInfo) ||
                BooleanUtils.isFalse(cardInfo.getIsOpened()) ||
                !commonSupplierUrlBo.getEmployeeOpenCard().getSubAccountName().equals(cardInfo.getSubAccountName())){
            //cardInfo = retryGetCardInfo(1, commonSupplierUrlBo, uid, logContext);
            //使用MQ延时队列进行获取，因为开卡后分销端是使用定时任务消费Q有一定的时间才会去进行开卡操作（即使开卡返回成功了不代表下游已经进行了开卡，需要获取开卡结果），我们延时去获取卡号
            GetOpenCardInfoMQBo getOpenCardInfoMQBo = new GetOpenCardInfoMQBo();
            getOpenCardInfoMQBo.setUid(openCardEmployeeModel.getUid());
            getOpenCardInfoMQBo.setBatchNo(openCardEmployeeModel.getBatchNo());
            getOpenCardInfoMQProducer.sendGetOpenCardInfo(getOpenCardInfoMQBo);
        }

        if (Objects.nonNull(cardInfo) && BooleanUtils.isTrue(cardInfo.getIsOpened())){
            MbOrgEmployeeOpenCardRecord existRecord = orgEmployeeOpenCardRecordService.selectByUid(openCardEmployeeModel.getUid());
            MbOrgEmployeeOpenCardRecord orgEmployeeOpenCardRecord = new MbOrgEmployeeOpenCardRecord();
            orgEmployeeOpenCardRecord.setSupplierUid(cardInfo.getUid());
            orgEmployeeOpenCardRecord.setPlatUid(openCardEmployeeModel.getUid());
            orgEmployeeOpenCardRecord.setName(cardInfo.getName());
            orgEmployeeOpenCardRecord.setOpenCardUid(this.getOpenCardUid(PREFIX_OBT, openCardEmployeeModel.getUid()));
            orgEmployeeOpenCardRecord.setSubAccountId(cardInfo.getSubAccountID());
            orgEmployeeOpenCardRecord.setSubAccountName(cardInfo.getSubAccountName());
            orgEmployeeOpenCardRecord.setSetDefaultSendConfig(true);
            orgEmployeeOpenCardRecord.setDatachangeCreatetime(new Date());
            orgEmployeeOpenCardRecord.setCorporateEntity(openCardEmployeeModel.getCorporateEntity());
            if (existRecord == null){
                orgEmployeeOpenCardRecord.setDatachangeLasttime(new Date());
                orgEmployeeOpenCardRecordService.insert(orgEmployeeOpenCardRecord);
                synchronized (this){
                     mbOpenCardMainTableMapper.addSuccessNum(openCardEmployeeModel.getBatchNo());
                }
                return;
            }
            orgEmployeeOpenCardRecord.setId(existRecord.getId());
            orgEmployeeOpenCardRecordService.update(orgEmployeeOpenCardRecord);
            synchronized (this){
                mbOpenCardMainTableMapper.addSuccessNum(openCardEmployeeModel.getBatchNo());
            }
        } else {
            addFailLog(openCardEmployeeModel.getUid(),openCardEmployeeModel.getName(), CTRIP_NOT_OPEN_CARD ,"1", openCardEmployeeModel.getBatchNo(),2);
        }
    }
    /**
     * 找到第一个有配置的父级公司
     * @param orgId
     * @return
     */
    @Override
    public List<SupplierCompanyModel> getParentConfig(String orgId){
      return getParentConfig(orgId, MAX_SIZE);
    }
    private List<SupplierCompanyModel> getParentConfig(String orgId, int recursionTimes){
        if (recursionTimes <= 0){
            return Collections.emptyList();
        }
        if (StringUtils.isBlank(orgId)){
            return Collections.emptyList();
        }
        MbOrgInfo mbOrgInfo = organizationInfoService.findFirstCompany(orgId);
        if (mbOrgInfo == null){
            return Collections.emptyList();
        }
        List<SupplierCompanyModel> companyConfigList =
                mbSupplierCompanyLoader.getSupplierCompanyConfig(mbOrgInfo.getOrgId(), CommonConstant.CTRIP_CODE);
        if (CollectionUtils.isEmpty(companyConfigList) && StringUtils.isNotBlank(mbOrgInfo.getParentId())){
            return getParentConfig(mbOrgInfo.getParentId(),recursionTimes - 1 );
        } else {
            return companyConfigList;
        }
    }


    /**
     * 判断当前租户是否可同步法人公司
     * @return
     */
    @Override
    public Boolean getCorporateEntitySyncFlag() {
        Boolean corporateEntityFlag = false;
        String tenantCodeStr = organizationApollo.getCorporateEntitySynchronizedTenant();
        if(Objects.nonNull(tenantCodeStr)) {
            //获取租户ID
            String tenantId = TenantContextHolder.getTenantId();
            String[] splitArr = tenantCodeStr.split("\\|");
            for(String split : splitArr){
                if(StringUtils.endsWithIgnoreCase(split, tenantId)) {
                    corporateEntityFlag = true;
                }
            }
        }
        return corporateEntityFlag;
    }
}
